<?php

namespace App\Admin\Actions\ShopUser;

use App\Library\Logic\OperateLogLogic;
use App\Models\ShopUserModel;
use Encore\Admin\Actions\Response;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;

class ShopUserAgentAction extends RowAction
{
    public $name = '经销商';

    public function __construct(int $flag = 0)
    {
        parent::__construct();
        $this->name = ($flag === 0 ? '开启' : '关闭') . $this->name;
    }

    /**
     * handle
     * @param ShopUserModel $model
     * @return Response
     * @throws \Exception
     */
    public function handle(ShopUserModel $model): Response
    {
        $model->agent = !$model->agent;
        $model->save();
        $k = 'agent:' . $model->user_id;
        if ($model->agent) cache([$k => 1]);
        else cache()->forget($k);
        mq('cacheUser', (string)$model->user_id);
        OperateLogLogic::add(Admin::user()->user_id, 'admin.shopUser.agent', ['agent' => !$model->agent]);
        return $this->response()->success('操作成功')->refresh();
    }
}
